﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataObject.DataAccess;
using DataObject.Database;

public partial class Pages_Report_OperatorReport : System.Web.UI.Page
{
    const string _groupName = "BoatID+ReservationID+ReservationCode+CheckInDate+Date+ShuttlePrice+ExtraService+CruisePackage+SubTotal+Deposit+Paid+CruiseCurrency+PaymentList";
    const string url = @"/Pages/Reports/OperatorReport.aspx?BoatID={0}&FromDate={1:d}&ToDate={2:d}&SortField={3}&SortOption={4}";

    #region Fields

    private GridViewHelper helper;

    #endregion

    #region Page Properties
    public DateTime FromDate { get; set; }
    public DateTime ToDate { get; set; }
    public string BoatID { get; set; }
    public string SortField { get; set; }
    public string SortOption { get; set; }

    public int PageIndex
    {
        get
        {
            if (Request["page"] != null)
            {
                return int.Parse(Request["page"].ToString());
            }
            return 1;
        }
    }

    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            List<BoatEntity> ls = BoatDAO.CreateInstant().GetAllBoats();
            ls.Insert(0, new BoatEntity() { BoatName = "All Boats", BoatID = String.Empty });

            ddlBoat.DataSource = ls;
            ddlBoat.DataTextField = "BoatName";
            ddlBoat.DataValueField = "BoatID";
            ddlBoat.DataBind();

            GetQueryString();
            Search();
        }
    }

    private void GetQueryString()
    {
        DateTime fromDate, toDate;

        // FromDate
        if (Request["FromDate"] != null && DateTime.TryParse(Request["FromDate"], System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out fromDate))
            FromDate = fromDate;
        else
            FromDate = DateTime.Today;

        // ToDate
        if (Request["ToDate"] != null && DateTime.TryParse(Request["ToDate"], System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out toDate))
            ToDate = toDate;
        else
            ToDate = DateTime.Today;

        this.txtFromDate.Text = FromDate.ToShortDate();
        this.txtToDate.Text = ToDate.ToShortDate();

        if (Request["BoatID"] != null)
            BoatID = Request["BoatID"];
        else
            BoatID = string.Empty;
        ddlBoat.SelectedValue = BoatID;
    }

    private void GetPropertyOnForm()
    {
        DateTime fromDate, toDate;

        // FromDate
        if (DateTime.TryParse(txtFromDate.Text, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out fromDate))
            FromDate = fromDate.Date;

        // ToDate
        if (DateTime.TryParse(txtToDate.Text, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out toDate))
            ToDate = toDate.Date;

        BoatID = ddlBoat.SelectedValue;
    }

    private void Search()
    {
        int count = 0;
        BuildOnGrid(out count);

        // Paging
        smartPager.PageSize = define.PageSize;
        smartPager.QueryStringKey = "page";
        smartPager.RowCount = count;
        smartPager.UrlFormatString = string.Format(url, BoatID, FromDate, ToDate, SortField, SortOption) + "&page={0}";
        smartPager.Visible = count > define.PageSize;
    }

    private void BuildOnGrid(out int count)
    {
        HashSet<string> hs = new HashSet<string>();
        IList<ViewOperatorReport> collection = ReservationDAO.CreateInstant().GetViewOperatorReport(FromDate, ToDate, BoatID, null, null, out count, hs);

        helper = new GridViewHelper(this.grv);
        helper.RegisterGroup(_groupName.Split('+'), true, true);
        helper.RegisterSummary("CabinPrice", SummaryOperation.Sum, _groupName);
        helper.GroupHeader += new GroupEvent(helper_GroupHeader);
        helper.GroupSummary += new GroupEvent(helper_GroupSummary);

        grv.DataSource = collection;
        grv.DataBind();
    }

    #region Events
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        GetPropertyOnForm();
        Response.Redirect(string.Format(url, BoatID, FromDate, ToDate, SortField, SortOption));
    }

    protected void btnPrint_Click(object sender, EventArgs e)
    {
        GetQueryString();
        int count = 0;
        BuildOnGrid(out count);

        System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
        string attachment = "attachment; filename=operator" + DateTime.Now.ToString("yyyyMMdd") + ".xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        Response.Charset = "";
        Response.ContentEncoding = System.Text.Encoding.Unicode;
        Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
        System.IO.StringWriter stw = new System.IO.StringWriter();
        HtmlTextWriter htextw = new HtmlTextWriter(stw);
        form.Controls.Add(grv); // gvParent là gridview 
        this.Controls.Add(form);
        form.RenderControl(htextw);

        Response.Write(stw.ToString());
        Response.End();
    }

    private void helper_GroupHeader(string groupName, object[] values, GridViewRow row)
    {
        if (groupName == _groupName)
        {
            row.BackColor = Color.FromName("#ffdf51");
            DateTime date;
            string dateString = String.Empty;
            if (DateTime.TryParse(values[4].ToString(), System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out date))
            {
                dateString = date.ToShortDate();
            }
            row.Cells[0].Text = "&nbsp;&nbsp;" + dateString + "&nbsp; - Boat:  " + values[0] + "&nbsp;&nbsp;[ Booking code: <a href=\"/Pages/Reservations/ReservationEdit.aspx?ReservationID=" + values[1] + "\">" + values[2] + "</a> ]";
        }
    }

    private void helper_GroupSummary(string groupName, object[] values, GridViewRow row)
    {
        if (groupName == _groupName)
        {
            row.BackColor = Color.FromName("#fff6cd");

            if (Convert.ToDateTime(values[3]).Date == Convert.ToDateTime(values[4]).Date)
            {
                decimal subTotal = Convert.ToDecimal(values[8]);
                decimal deposit = Convert.ToDecimal(values[9]);
                decimal paid = Convert.ToDecimal(values[10]);
                decimal balance = subTotal - deposit - paid;
                row.Cells[0].HorizontalAlign = HorizontalAlign.Right;
                row.Cells[0].Text = String.Format(
                    "<div style=\"font-family: Courier New\">" +
                    "<div>Shuttle: ({7}) {0}</div>" +
                    "<div>Extra service: {1}</div>" +
                    "<div>Cruise package: {2}</div>" +
                    "<hr />" +
                    "<div>Sub Total: {3}</div>" +
                    "<div>Deposit: {4}</div>" +
                    "<div>Paid: {5}</div>" +
                    "<div>Balance: {6}</div>" +
                    "{8}</div>",
                    Convert.ToDecimal(values[5]).ToString("#,##0.##").PadLeft(10, "&nbsp;"),
                    Convert.ToDecimal(values[6]).ToString("#,##0.##").PadLeft(10, "&nbsp;"),
                    Convert.ToDecimal(values[7]).ToString("#,##0.##").PadLeft(10, "&nbsp;"),
                    subTotal.ToString("#,##0.##").PadLeft(16, "&nbsp;"),
                    deposit.ToString("#,##0.##").PadLeft(16, "&nbsp;"),
                    paid.ToString("#,##0.##").PadLeft(16, "&nbsp;"),
                    balance.ToString("#,##0.##").PadLeft(16, "&nbsp;"),
                    ((CurrencyEnum)values[11]).GetStringValue(),
                    values[12]);
            }
        }
    } 
    #endregion


}
